{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Surname Classification \n",
    "\n",
    "In this example, we see surname classification. \n",
    "\n",
    "This is a modified version of the main example in which we use the PackedSequences data structure that PyTorch provides.  While PackedSequences is a useful data structure, seeing what's happening with column indexing is very useful. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from argparse import Namespace\n",
    "import os\n",
    "import json\n",
    "\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "import torch.optim as optim\n",
    "from torch.utils.data import Dataset, DataLoader\n",
    "from tqdm import tqdm_notebook"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Vocabulary, Vectorizer, Dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Vocabulary(object):\n",
    "    \"\"\"Class to process text and extract vocabulary for mapping\"\"\"\n",
    "\n",
    "    def __init__(self, token_to_idx=None):\n",
    "        \"\"\"\n",
    "        Args:\n",
    "            token_to_idx (dict): a pre-existing map of tokens to indices\n",
    "        \"\"\"\n",
    "\n",
    "        if token_to_idx is None:\n",
    "            token_to_idx = {}\n",
    "        self._token_to_idx = token_to_idx\n",
    "\n",
    "        self._idx_to_token = {idx: token \n",
    "                              for token, idx in self._token_to_idx.items()}\n",
    "        \n",
    "    def to_serializable(self):\n",
    "        \"\"\" returns a dictionary that can be serialized \"\"\"\n",
    "        return {'token_to_idx': self._token_to_idx}\n",
    "\n",
    "    @classmethod\n",
    "    def from_serializable(cls, contents):\n",
    "        \"\"\" instantiates the Vocabulary from a serialized dictionary \"\"\"\n",
    "        return cls(**contents)\n",
    "\n",
    "    def add_token(self, token):\n",
    "        \"\"\"Update mapping dicts based on the token.\n",
    "\n",
    "        Args:\n",
    "            token (str): the item to add into the Vocabulary\n",
    "        Returns:\n",
    "            index (int): the integer corresponding to the token\n",
    "        \"\"\"\n",
    "        if token in self._token_to_idx:\n",
    "            index = self._token_to_idx[token]\n",
    "        else:\n",
    "            index = len(self._token_to_idx)\n",
    "            self._token_to_idx[token] = index\n",
    "            self._idx_to_token[index] = token\n",
    "        return index\n",
    "            \n",
    "    def add_many(self, tokens):\n",
    "        \"\"\"Add a list of tokens into the Vocabulary\n",
    "        \n",
    "        Args:\n",
    "            tokens (list): a list of string tokens\n",
    "        Returns:\n",
    "            indices (list): a list of indices corresponding to the tokens\n",
    "        \"\"\"\n",
    "        return [self.add_token(token) for token in tokens]\n",
    "\n",
    "    def lookup_token(self, token):\n",
    "        \"\"\"Retrieve the index associated with the token \n",
    "        \n",
    "        Args:\n",
    "            token (str): the token to look up \n",
    "        Returns:\n",
    "            index (int): the index corresponding to the token\n",
    "        \"\"\"\n",
    "        return self._token_to_idx[token]\n",
    "\n",
    "    def lookup_index(self, index):\n",
    "        \"\"\"Return the token associated with the index\n",
    "        \n",
    "        Args: \n",
    "            index (int): the index to look up\n",
    "        Returns:\n",
    "            token (str): the token corresponding to the index\n",
    "        Raises:\n",
    "            KeyError: if the index is not in the Vocabulary\n",
    "        \"\"\"\n",
    "        if index not in self._idx_to_token:\n",
    "            raise KeyError(\"the index (%d) is not in the Vocabulary\" % index)\n",
    "        return self._idx_to_token[index]\n",
    "\n",
    "    def __str__(self):\n",
    "        return \"<Vocabulary(size=%d)>\" % len(self)\n",
    "\n",
    "    def __len__(self):\n",
    "        return len(self._token_to_idx)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "class SequenceVocabulary(Vocabulary):\n",
    "    def __init__(self, token_to_idx=None, unk_token=\"<UNK>\",\n",
    "                 mask_token=\"<MASK>\", begin_seq_token=\"<BEGIN>\",\n",
    "                 end_seq_token=\"<END>\"):\n",
    "\n",
    "        super(SequenceVocabulary, self).__init__(token_to_idx)\n",
    "\n",
    "        self._mask_token = mask_token\n",
    "        self._unk_token = unk_token\n",
    "        self._begin_seq_token = begin_seq_token\n",
    "        self._end_seq_token = end_seq_token\n",
    "\n",
    "        self.mask_index = self.add_token(self._mask_token)\n",
    "        self.unk_index = self.add_token(self._unk_token)\n",
    "        self.begin_seq_index = self.add_token(self._begin_seq_token)\n",
    "        self.end_seq_index = self.add_token(self._end_seq_token)\n",
    "\n",
    "    def to_serializable(self):\n",
    "        contents = super(SequenceVocabulary, self).to_serializable()\n",
    "        contents.update({'unk_token': self._unk_token,\n",
    "                         'mask_token': self._mask_token,\n",
    "                         'begin_seq_token': self._begin_seq_token,\n",
    "                         'end_seq_token': self._end_seq_token})\n",
    "        return contents\n",
    "\n",
    "    def lookup_token(self, token):\n",
    "        \"\"\"Retrieve the index associated with the token \n",
    "          or the UNK index if token isn't present.\n",
    "        \n",
    "        Args:\n",
    "            token (str): the token to look up \n",
    "        Returns:\n",
    "            index (int): the index corresponding to the token\n",
    "        Notes:\n",
    "            `unk_index` needs to be >=0 (having been added into the Vocabulary) \n",
    "              for the UNK functionality \n",
    "        \"\"\"\n",
    "        if self.unk_index >= 0:\n",
    "            return self._token_to_idx.get(token, self.unk_index)\n",
    "        else:\n",
    "            return self._token_to_idx[token]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "class SurnameVectorizer(object):\n",
    "    \"\"\" The Vectorizer which coordinates the Vocabularies and puts them to use\"\"\"   \n",
    "    def __init__(self, char_vocab, nationality_vocab):\n",
    "        \"\"\"\n",
    "        Args:\n",
    "            char_vocab (Vocabulary): maps characters to integers\n",
    "            nationality_vocab (Vocabulary): maps nationalities to integers\n",
    "        \"\"\"\n",
    "        self.char_vocab = char_vocab\n",
    "        self.nationality_vocab = nationality_vocab\n",
    "\n",
    "    def vectorize(self, surname, vector_length=-1):\n",
    "        \"\"\"\n",
    "        Args:\n",
    "            title (str): the string of characters\n",
    "            vector_length (int): an argument for forcing the length of index vector\n",
    "        \"\"\"\n",
    "        indices = [self.char_vocab.begin_seq_index]\n",
    "        indices.extend(self.char_vocab.lookup_token(token) \n",
    "                       for token in surname)\n",
    "        indices.append(self.char_vocab.end_seq_index)\n",
    "\n",
    "        if vector_length < 0:\n",
    "            vector_length = len(indices)\n",
    "\n",
    "        out_vector = np.zeros(vector_length, dtype=np.int64)         \n",
    "        out_vector[:len(indices)] = indices\n",
    "        out_vector[len(indices):] = self.char_vocab.mask_index\n",
    "        \n",
    "        return out_vector, len(indices)\n",
    "\n",
    "    @classmethod\n",
    "    def from_dataframe(cls, surname_df):\n",
    "        \"\"\"Instantiate the vectorizer from the dataset dataframe\n",
    "        \n",
    "        Args:\n",
    "            surname_df (pandas.DataFrame): the surnames dataset\n",
    "        Returns:\n",
    "            an instance of the SurnameVectorizer\n",
    "        \"\"\"\n",
    "        char_vocab = SequenceVocabulary()\n",
    "        nationality_vocab = Vocabulary()\n",
    "\n",
    "        for index, row in surname_df.iterrows():\n",
    "            for char in row.surname:\n",
    "                char_vocab.add_token(char)\n",
    "            nationality_vocab.add_token(row.nationality)\n",
    "\n",
    "        return cls(char_vocab, nationality_vocab)\n",
    "\n",
    "    @classmethod\n",
    "    def from_serializable(cls, contents):\n",
    "        char_vocab = SequenceVocabulary.from_serializable(contents['char_vocab'])\n",
    "        nat_vocab =  Vocabulary.from_serializable(contents['nationality_vocab'])\n",
    "\n",
    "        return cls(char_vocab=char_vocab, nationality_vocab=nat_vocab)\n",
    "\n",
    "    def to_serializable(self):\n",
    "        return {'char_vocab': self.char_vocab.to_serializable(), \n",
    "                'nationality_vocab': self.nationality_vocab.to_serializable()}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "class SurnameDataset(Dataset):\n",
    "    def __init__(self, surname_df, vectorizer):\n",
    "        \"\"\"\n",
    "        Args:\n",
    "            surname_df (pandas.DataFrame): the dataset\n",
    "            vectorizer (SurnameVectorizer): vectorizer instatiated from dataset\n",
    "        \"\"\"\n",
    "        self.surname_df = surname_df \n",
    "        self._vectorizer = vectorizer\n",
    "\n",
    "        self._max_seq_length = max(map(len, self.surname_df.surname)) + 2\n",
    "\n",
    "        self.train_df = self.surname_df[self.surname_df.split=='train']\n",
    "        self.train_size = len(self.train_df)\n",
    "\n",
    "        self.val_df = self.surname_df[self.surname_df.split=='val']\n",
    "        self.validation_size = len(self.val_df)\n",
    "\n",
    "        self.test_df = self.surname_df[self.surname_df.split=='test']\n",
    "        self.test_size = len(self.test_df)\n",
    "\n",
    "        self._lookup_dict = {'train': (self.train_df, self.train_size), \n",
    "                             'val': (self.val_df, self.validation_size), \n",
    "                             'test': (self.test_df, self.test_size)}\n",
    "\n",
    "        self.set_split('train')\n",
    "        \n",
    "        # Class weights\n",
    "        class_counts = self.train_df.nationality.value_counts().to_dict()\n",
    "        def sort_key(item):\n",
    "            return self._vectorizer.nationality_vocab.lookup_token(item[0])\n",
    "        sorted_counts = sorted(class_counts.items(), key=sort_key)\n",
    "        frequencies = [count for _, count in sorted_counts]\n",
    "        self.class_weights = 1.0 / torch.tensor(frequencies, dtype=torch.float32)\n",
    "\n",
    "        \n",
    "    @classmethod\n",
    "    def load_dataset_and_make_vectorizer(cls, surname_csv):\n",
    "        \"\"\"Load dataset and make a new vectorizer from scratch\n",
    "        \n",
    "        Args:\n",
    "            surname_csv (str): location of the dataset\n",
    "        Returns:\n",
    "            an instance of SurnameDataset\n",
    "        \"\"\"\n",
    "        surname_df = pd.read_csv(surname_csv)\n",
    "        train_surname_df = surname_df[surname_df.split=='train']\n",
    "        return cls(surname_df, SurnameVectorizer.from_dataframe(train_surname_df))\n",
    "        \n",
    "    @classmethod\n",
    "    def load_dataset_and_load_vectorizer(cls, surname_csv, vectorizer_filepath):\n",
    "        \"\"\"Load dataset and the corresponding vectorizer. \n",
    "        Used in the case in the vectorizer has been cached for re-use\n",
    "        \n",
    "        Args:\n",
    "            surname_csv (str): location of the dataset\n",
    "            vectorizer_filepath (str): location of the saved vectorizer\n",
    "        Returns:\n",
    "            an instance of SurnameDataset\n",
    "        \"\"\"\n",
    "        surname_df = pd.read_csv(surname_csv)\n",
    "        vectorizer = cls.load_vectorizer_only(vectorizer_filepath)\n",
    "        return cls(surname_df, vectorizer)\n",
    "\n",
    "    @staticmethod\n",
    "    def load_vectorizer_only(vectorizer_filepath):\n",
    "        \"\"\"a static method for loading the vectorizer from file\n",
    "        \n",
    "        Args:\n",
    "            vectorizer_filepath (str): the location of the serialized vectorizer\n",
    "        Returns:\n",
    "            an instance of SurnameVectorizer\n",
    "        \"\"\"\n",
    "        with open(vectorizer_filepath) as fp:\n",
    "            return SurnameVectorizer.from_serializable(json.load(fp))\n",
    "\n",
    "    def save_vectorizer(self, vectorizer_filepath):\n",
    "        \"\"\"saves the vectorizer to disk using json\n",
    "        \n",
    "        Args:\n",
    "            vectorizer_filepath (str): the location to save the vectorizer\n",
    "        \"\"\"\n",
    "        with open(vectorizer_filepath, \"w\") as fp:\n",
    "            json.dump(self._vectorizer.to_serializable(), fp)\n",
    "\n",
    "    def get_vectorizer(self):\n",
    "        \"\"\" returns the vectorizer \"\"\"\n",
    "        return self._vectorizer\n",
    "\n",
    "    def set_split(self, split=\"train\"):\n",
    "        self._target_split = split\n",
    "        self._target_df, self._target_size = self._lookup_dict[split]\n",
    "\n",
    "    def __len__(self):\n",
    "        return self._target_size\n",
    "\n",
    "    def __getitem__(self, index):\n",
    "        \"\"\"the primary entry point method for PyTorch datasets\n",
    "        \n",
    "        Args:\n",
    "            index (int): the index to the data point \n",
    "        Returns:\n",
    "            a dictionary holding the data point's:\n",
    "                features (x_data)\n",
    "                label (y_target)\n",
    "                feature length (x_length)\n",
    "        \"\"\"\n",
    "        row = self._target_df.iloc[index]\n",
    "        \n",
    "        surname_vector, vec_length = \\\n",
    "            self._vectorizer.vectorize(row.surname, self._max_seq_length)\n",
    "        \n",
    "        nationality_index = \\\n",
    "            self._vectorizer.nationality_vocab.lookup_token(row.nationality)\n",
    "\n",
    "        return {'x_data': surname_vector, \n",
    "                'y_target': nationality_index, \n",
    "                'x_length': vec_length}\n",
    "\n",
    "    def get_num_batches(self, batch_size):\n",
    "        \"\"\"Given a batch size, return the number of batches in the dataset\n",
    "        \n",
    "        Args:\n",
    "            batch_size (int)\n",
    "        Returns:\n",
    "            number of batches in the dataset\n",
    "        \"\"\"\n",
    "        return len(self) // batch_size\n",
    "\n",
    "    \n",
    "\n",
    "def generate_batches(dataset, batch_size, shuffle=True,\n",
    "                     drop_last=True, device=\"cpu\"): \n",
    "    \"\"\"\n",
    "    A generator function which wraps the PyTorch DataLoader. It will \n",
    "      ensure each tensor is on the write device location.\n",
    "    \"\"\"\n",
    "    dataloader = DataLoader(dataset=dataset, batch_size=batch_size,\n",
    "                            shuffle=shuffle, drop_last=drop_last)\n",
    "\n",
    "    for data_dict in dataloader:\n",
    "        out_data_dict = {}\n",
    "        for name, tensor in data_dict.items():\n",
    "            out_data_dict[name] = data_dict[name].to(device)\n",
    "        yield out_data_dict"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "def column_gather(y_out, x_lengths):\n",
    "    '''Get a specific vector from each batch datapoint in `y_out`.\n",
    "\n",
    "    More precisely, iterate over batch row indices, get the vector that's at\n",
    "    the position indicated by the corresponding value in `x_lengths` at the row\n",
    "    index.\n",
    "\n",
    "    Args:\n",
    "        y_out (torch.FloatTensor, torch.cuda.FloatTensor)\n",
    "            shape: (batch, sequence, feature)\n",
    "        x_lengths (torch.LongTensor, torch.cuda.LongTensor)\n",
    "            shape: (batch,)\n",
    "\n",
    "    Returns:\n",
    "        y_out (torch.FloatTensor, torch.cuda.FloatTensor)\n",
    "            shape: (batch, feature)\n",
    "    '''\n",
    "    x_lengths = x_lengths.long().detach().cpu().numpy() - 1\n",
    "\n",
    "    out = []\n",
    "    for batch_index, column_index in enumerate(x_lengths):\n",
    "        out.append(y_out[batch_index, column_index])\n",
    "\n",
    "    return torch.stack(out)\n",
    "\n",
    "\n",
    "class ElmanRNN(nn.Module):\n",
    "    \"\"\" an Elman RNN built using the RNNCell \"\"\"\n",
    "    def __init__(self, input_size, hidden_size, batch_first=False):\n",
    "        \"\"\"\n",
    "        Args:\n",
    "            input_size (int): size of the input vectors\n",
    "            hidden_size (int): size of the hidden state vectors\n",
    "            bathc_first (bool): whether the 0th dimension is batch\n",
    "        \"\"\"\n",
    "        super(ElmanRNN, self).__init__()\n",
    "        \n",
    "        self.rnn_cell = nn.RNNCell(input_size, hidden_size)\n",
    "        \n",
    "        self.batch_first = batch_first\n",
    "        self.hidden_size = hidden_size\n",
    "\n",
    "    def _initial_hidden(self, batch_size):\n",
    "        return torch.zeros((batch_size, self.hidden_size))\n",
    "\n",
    "    def forward(self, x_in, initial_hidden=None):\n",
    "        \"\"\"The forward pass of the ElmanRNN\n",
    "        \n",
    "        Args:\n",
    "            x_in (torch.Tensor): an input data tensor. \n",
    "                If self.batch_first: x_in.shape = (batch, seq_size, feat_size)\n",
    "                Else: x_in.shape = (seq_size, batch, feat_size)\n",
    "            initial_hidden (torch.Tensor): the initial hidden state for the RNN\n",
    "        Returns:\n",
    "            hiddens (torch.Tensor): The outputs of the RNN at each time step. \n",
    "                If self.batch_first: hiddens.shape = (batch, seq_size, hidden_size)\n",
    "                Else: hiddens.shape = (seq_size, batch, hidden_size)\n",
    "        \"\"\"\n",
    "        if self.batch_first:\n",
    "            batch_size, seq_size, feat_size = x_in.size()\n",
    "            x_in = x_in.permute(1, 0, 2)\n",
    "        else:\n",
    "            seq_size, batch_size, feat_size = x_in.size()\n",
    "    \n",
    "        hiddens = []\n",
    "\n",
    "        if initial_hidden is None:\n",
    "            initial_hidden = self._initial_hidden(batch_size)\n",
    "            initial_hidden = initial_hidden.to(x_in.device)\n",
    "\n",
    "        hidden_t = initial_hidden\n",
    "                    \n",
    "        for t in range(seq_size):\n",
    "            hidden_t = self.rnn_cell(x_in[t], hidden_t)\n",
    "            hiddens.append(hidden_t)\n",
    "            \n",
    "        hiddens = torch.stack(hiddens)\n",
    "\n",
    "        if self.batch_first:\n",
    "            hiddens = hiddens.permute(1, 0, 2)\n",
    "\n",
    "        return hiddens\n",
    "\n",
    "\n",
    "\n",
    "class SurnameClassifier(nn.Module):\n",
    "    \"\"\" A Classifier with an RNN to extract features and an MLP to classify \"\"\"\n",
    "    def __init__(self, embedding_size, num_embeddings, num_classes,\n",
    "                 rnn_hidden_size, batch_first=True, padding_idx=0):\n",
    "        \"\"\"\n",
    "        Args:\n",
    "            embedding_size (int): The size of the character embeddings\n",
    "            num_embeddings (int): The number of characters to embed\n",
    "            num_classes (int): The size of the prediction vector \n",
    "                Note: the number of nationalities\n",
    "            rnn_hidden_size (int): The size of the RNN's hidden state\n",
    "            batch_first (bool): Informs whether the input tensors will \n",
    "                have batch or the sequence on the 0th dimension\n",
    "            padding_idx (int): The index for the tensor padding; \n",
    "                see torch.nn.Embedding\n",
    "        \"\"\"\n",
    "        super(SurnameClassifier, self).__init__()\n",
    "\n",
    "        self.emb = nn.Embedding(num_embeddings=num_embeddings,\n",
    "                                embedding_dim=embedding_size,\n",
    "                                padding_idx=padding_idx)\n",
    "        self.rnn = ElmanRNN(input_size=embedding_size,\n",
    "                             hidden_size=rnn_hidden_size,\n",
    "                             batch_first=batch_first)\n",
    "        self.fc1 = nn.Linear(in_features=rnn_hidden_size,\n",
    "                         out_features=rnn_hidden_size)\n",
    "        self.fc2 = nn.Linear(in_features=rnn_hidden_size,\n",
    "                          out_features=num_classes)\n",
    "\n",
    "    def forward(self, x_in, x_lengths=None, apply_softmax=False):\n",
    "        \"\"\"The forward pass of the classifier\n",
    "        \n",
    "        Args:\n",
    "            x_in (torch.Tensor): an input data tensor. \n",
    "                x_in.shape should be (batch, input_dim)\n",
    "            x_lengths (torch.Tensor): the lengths of each sequence in the batch.\n",
    "                They are used to find the final vector of each sequence\n",
    "            apply_softmax (bool): a flag for the softmax activation\n",
    "                should be false if used with the Cross Entropy losses\n",
    "        Returns:\n",
    "            the resulting tensor. tensor.shape should be (batch, output_dim)\n",
    "        \"\"\"\n",
    "        x_embedded = self.emb(x_in)\n",
    "        y_out = self.rnn(x_embedded)\n",
    "\n",
    "        if x_lengths is not None:\n",
    "            y_out = column_gather(y_out, x_lengths)\n",
    "        else:\n",
    "            y_out = y_out[:, -1, :]\n",
    "\n",
    "        y_out = F.relu(self.fc1(F.dropout(y_out, 0.5)))\n",
    "        y_out = self.fc2(F.dropout(y_out, 0.5))\n",
    "\n",
    "        if apply_softmax:\n",
    "            y_out = F.softmax(y_out, dim=1)\n",
    "\n",
    "        return y_out"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "def set_seed_everywhere(seed, cuda):\n",
    "    np.random.seed(seed)\n",
    "    torch.manual_seed(seed)\n",
    "    if cuda:\n",
    "        torch.cuda.manual_seed_all(seed)\n",
    "\n",
    "def handle_dirs(dirpath):\n",
    "    if not os.path.exists(dirpath):\n",
    "        os.makedirs(dirpath)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Settings"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "code_folding": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Using CUDA: True\n"
     ]
    }
   ],
   "source": [
    "args = Namespace(\n",
    "    # Data and path information\n",
    "    surname_csv=\"data/surnames/surnames_with_splits.csv\",\n",
    "    vectorizer_file=\"vectorizer.json\",\n",
    "    model_state_file=\"model.pth\",\n",
    "    save_dir=\"model_storage/ch6/surname_classification\",\n",
    "    # Model hyper parameter\n",
    "    char_embedding_size=100,\n",
    "    rnn_hidden_size=64,\n",
    "    # Training hyper parameter\n",
    "    num_epochs=100,\n",
    "    learning_rate=1e-3,\n",
    "    batch_size=64,\n",
    "    seed=1337,\n",
    "    early_stopping_criteria=5,\n",
    "    # Runtime hyper parameter\n",
    "    cuda=True,\n",
    "    catch_keyboard_interrupt=True,\n",
    "    reload_from_files=False,\n",
    "    expand_filepaths_to_save_dir=True,\n",
    ")\n",
    "\n",
    "# Check CUDA\n",
    "if not torch.cuda.is_available():\n",
    "    args.cuda = False\n",
    "\n",
    "args.device = torch.device(\"cuda\" if args.cuda else \"cpu\")\n",
    "    \n",
    "print(\"Using CUDA: {}\".format(args.cuda))\n",
    "\n",
    "\n",
    "if args.expand_filepaths_to_save_dir:\n",
    "    args.vectorizer_file = os.path.join(args.save_dir,\n",
    "                                        args.vectorizer_file)\n",
    "\n",
    "    args.model_state_file = os.path.join(args.save_dir,\n",
    "                                         args.model_state_file)\n",
    "    \n",
    "# Set seed for reproducibility\n",
    "set_seed_everywhere(args.seed, args.cuda)\n",
    "\n",
    "# handle dirs\n",
    "handle_dirs(args.save_dir)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "code_folding": [
     0,
     4
    ]
   },
   "outputs": [],
   "source": [
    "if args.reload_from_files and os.path.exists(args.vectorizer_file):\n",
    "    # training from a checkpoint\n",
    "    dataset = SurnameDataset.load_dataset_and_load_vectorizer(args.surname_csv, \n",
    "                                                              args.vectorizer_file)\n",
    "else:\n",
    "    # create dataset and vectorizer\n",
    "    dataset = SurnameDataset.load_dataset_and_make_vectorizer(args.surname_csv)\n",
    "    dataset.save_vectorizer(args.vectorizer_file)\n",
    "\n",
    "vectorizer = dataset.get_vectorizer()\n",
    "\n",
    "classifier = SurnameClassifier(embedding_size=args.char_embedding_size, \n",
    "                               num_embeddings=len(vectorizer.char_vocab),\n",
    "                               num_classes=len(vectorizer.nationality_vocab),\n",
    "                               rnn_hidden_size=args.rnn_hidden_size,\n",
    "                               padding_idx=vectorizer.char_vocab.mask_index)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Training Routine"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "code_folding": []
   },
   "outputs": [],
   "source": [
    "def make_train_state(args):\n",
    "    return {'stop_early': False,\n",
    "            'early_stopping_step': 0,\n",
    "            'early_stopping_best_val': 1e8,\n",
    "            'learning_rate': args.learning_rate,\n",
    "            'epoch_index': 0,\n",
    "            'train_loss': [],\n",
    "            'train_acc': [],\n",
    "            'val_loss': [],\n",
    "            'val_acc': [],\n",
    "            'test_loss': -1,\n",
    "            'test_acc': -1,\n",
    "            'model_filename': args.model_state_file}\n",
    "\n",
    "\n",
    "def update_train_state(args, model, train_state):\n",
    "    \"\"\"Handle the training state updates.\n",
    "\n",
    "    Components:\n",
    "     - Early Stopping: Prevent overfitting.\n",
    "     - Model Checkpoint: Model is saved if the model is better\n",
    "    \n",
    "    :param args: main arguments\n",
    "    :param model: model to train\n",
    "    :param train_state: a dictionary representing the training state values\n",
    "    :returns:\n",
    "        a new train_state\n",
    "    \"\"\"\n",
    "\n",
    "    # Save one model at least\n",
    "    if train_state['epoch_index'] == 0:\n",
    "        torch.save(model.state_dict(), train_state['model_filename'])\n",
    "        train_state['stop_early'] = False\n",
    "\n",
    "    # Save model if performance improved\n",
    "    elif train_state['epoch_index'] >= 1:\n",
    "        loss_tm1, loss_t = train_state['val_loss'][-2:]\n",
    "         \n",
    "        # If loss worsened\n",
    "        if loss_t >= loss_tm1:\n",
    "            # Update step\n",
    "            train_state['early_stopping_step'] += 1\n",
    "        # Loss decreased\n",
    "        else:\n",
    "            # Save the best model\n",
    "            if loss_t < train_state['early_stopping_best_val']:\n",
    "                torch.save(model.state_dict(), train_state['model_filename'])\n",
    "                train_state['early_stopping_best_val'] = loss_t\n",
    "\n",
    "            # Reset early stopping step\n",
    "            train_state['early_stopping_step'] = 0\n",
    "\n",
    "        # Stop early ?\n",
    "        train_state['stop_early'] = \\\n",
    "            train_state['early_stopping_step'] >= args.early_stopping_criteria\n",
    "\n",
    "    return train_state\n",
    "\n",
    "\n",
    "def compute_accuracy(y_pred, y_target):\n",
    "    _, y_pred_indices = y_pred.max(dim=1)\n",
    "    n_correct = torch.eq(y_pred_indices, y_target).sum().item()\n",
    "    return n_correct / len(y_pred_indices) * 100"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "code_folding": []
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "422190251f8640a0a1d8a988eb4baa05",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, description='training routine', style=ProgressStyle(description_width='ini…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "ac4097f5be4d4e3aac37106c824119ca",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, description='split=train', max=120, style=ProgressStyle(description_width=…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "8d748260aa5f4952831b492d9113d619",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, description='split=val', max=25, style=ProgressStyle(description_width='in…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Exiting loop\n"
     ]
    }
   ],
   "source": [
    "classifier = classifier.to(args.device)\n",
    "dataset.class_weights = dataset.class_weights.to(args.device)\n",
    "    \n",
    "loss_func = nn.CrossEntropyLoss(dataset.class_weights)\n",
    "optimizer = optim.Adam(classifier.parameters(), lr=args.learning_rate)\n",
    "scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer=optimizer,\n",
    "                                           mode='min', factor=0.5,\n",
    "                                           patience=1)\n",
    "\n",
    "train_state = make_train_state(args)\n",
    "\n",
    "epoch_bar = tqdm_notebook(desc='training routine', \n",
    "                          total=args.num_epochs,\n",
    "                          position=0)\n",
    "\n",
    "dataset.set_split('train')\n",
    "train_bar = tqdm_notebook(desc='split=train',\n",
    "                          total=dataset.get_num_batches(args.batch_size), \n",
    "                          position=1, \n",
    "                          leave=True)\n",
    "dataset.set_split('val')\n",
    "val_bar = tqdm_notebook(desc='split=val',\n",
    "                        total=dataset.get_num_batches(args.batch_size), \n",
    "                        position=1, \n",
    "                        leave=True)\n",
    "\n",
    "try:\n",
    "    for epoch_index in range(args.num_epochs):\n",
    "        train_state['epoch_index'] = epoch_index\n",
    "\n",
    "        # Iterate over training dataset\n",
    "\n",
    "        # setup: batch generator, set loss and acc to 0, set train mode on\n",
    "        dataset.set_split('train')\n",
    "        batch_generator = generate_batches(dataset, \n",
    "                                           batch_size=args.batch_size, \n",
    "                                           device=args.device)\n",
    "        running_loss = 0.0\n",
    "        running_acc = 0.0\n",
    "        classifier.train()\n",
    "\n",
    "        for batch_index, batch_dict in enumerate(batch_generator):\n",
    "            # the training routine is these 5 steps:\n",
    "\n",
    "            # --------------------------------------    \n",
    "            # step 1. zero the gradients\n",
    "            optimizer.zero_grad()\n",
    "\n",
    "            # step 2. compute the output\n",
    "            y_pred = classifier(x_in=batch_dict['x_data'], \n",
    "                                x_lengths=batch_dict['x_length'])\n",
    "\n",
    "            # step 3. compute the loss\n",
    "            loss = loss_func(y_pred, batch_dict['y_target'])\n",
    "    \n",
    "            running_loss += (loss.item() - running_loss) / (batch_index + 1)\n",
    "\n",
    "            # step 4. use loss to produce gradients\n",
    "            loss.backward()\n",
    "\n",
    "            # step 5. use optimizer to take gradient step\n",
    "            optimizer.step()\n",
    "            # -----------------------------------------\n",
    "            # compute the accuracy\n",
    "            acc_t = compute_accuracy(y_pred, batch_dict['y_target'])\n",
    "            running_acc += (acc_t - running_acc) / (batch_index + 1)\n",
    "\n",
    "            # update bar\n",
    "            train_bar.set_postfix(loss=running_loss, acc=running_acc, epoch=epoch_index)\n",
    "            train_bar.update()\n",
    "\n",
    "        train_state['train_loss'].append(running_loss)\n",
    "        train_state['train_acc'].append(running_acc)\n",
    "\n",
    "        # Iterate over val dataset\n",
    "\n",
    "        # setup: batch generator, set loss and acc to 0; set eval mode on\n",
    "\n",
    "        dataset.set_split('val')\n",
    "        batch_generator = generate_batches(dataset, \n",
    "                                           batch_size=args.batch_size, \n",
    "                                           device=args.device)\n",
    "        running_loss = 0.\n",
    "        running_acc = 0.\n",
    "        classifier.eval()\n",
    "\n",
    "        for batch_index, batch_dict in enumerate(batch_generator):\n",
    "            # compute the output\n",
    "            y_pred = classifier(x_in=batch_dict['x_data'], \n",
    "                                x_lengths=batch_dict['x_length'])\n",
    "\n",
    "            # step 3. compute the loss\n",
    "            loss = loss_func(y_pred, batch_dict['y_target'])\n",
    "            running_loss += (loss.item() - running_loss) / (batch_index + 1)\n",
    "\n",
    "            # compute the accuracy\n",
    "            acc_t = compute_accuracy(y_pred, batch_dict['y_target'])\n",
    "            running_acc += (acc_t - running_acc) / (batch_index + 1)\n",
    "            val_bar.set_postfix(loss=running_loss, acc=running_acc, epoch=epoch_index)\n",
    "            val_bar.update()\n",
    "\n",
    "        train_state['val_loss'].append(running_loss)\n",
    "        train_state['val_acc'].append(running_acc)\n",
    "\n",
    "        train_state = update_train_state(args=args, model=classifier, \n",
    "                                         train_state=train_state)\n",
    "\n",
    "        scheduler.step(train_state['val_loss'][-1])\n",
    "\n",
    "        train_bar.n = 0\n",
    "        val_bar.n = 0\n",
    "        epoch_bar.update()\n",
    "\n",
    "        if train_state['stop_early']:\n",
    "            break\n",
    "            \n",
    "except KeyboardInterrupt:\n",
    "    print(\"Exiting loop\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "# compute the loss & accuracy on the test set using the best available model\n",
    "\n",
    "classifier.load_state_dict(torch.load(train_state['model_filename']))\n",
    "\n",
    "classifier = classifier.to(args.device)\n",
    "dataset.class_weights = dataset.class_weights.to(args.device)\n",
    "loss_func = nn.CrossEntropyLoss(dataset.class_weights)\n",
    "\n",
    "dataset.set_split('test')\n",
    "batch_generator = generate_batches(dataset, \n",
    "                                   batch_size=args.batch_size, \n",
    "                                   device=args.device)\n",
    "running_loss = 0.\n",
    "running_acc = 0.\n",
    "classifier.eval()\n",
    "\n",
    "for batch_index, batch_dict in enumerate(batch_generator):\n",
    "    # compute the output\n",
    "    y_pred =  classifier(batch_dict['x_data'],\n",
    "                         x_lengths=batch_dict['x_length'])\n",
    "    \n",
    "    # compute the loss\n",
    "    loss = loss_func(y_pred, batch_dict['y_target'])\n",
    "    loss_t = loss.item()\n",
    "    running_loss += (loss_t - running_loss) / (batch_index + 1)\n",
    "\n",
    "    # compute the accuracy\n",
    "    acc_t = compute_accuracy(y_pred, batch_dict['y_target'])\n",
    "    running_acc += (acc_t - running_acc) / (batch_index + 1)\n",
    "\n",
    "train_state['test_loss'] = running_loss\n",
    "train_state['test_acc'] = running_acc"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Test loss: 1.859536194801331;\n",
      "Test Accuracy: 41.5\n"
     ]
    }
   ],
   "source": [
    "print(\"Test loss: {};\".format(train_state['test_loss']))\n",
    "print(\"Test Accuracy: {}\".format(train_state['test_acc']))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Inference"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "def predict_nationality(surname, classifier, vectorizer):\n",
    "    vectorized_surname, vec_length = vectorizer.vectorize(surname)\n",
    "    vectorized_surname = torch.tensor(vectorized_surname).unsqueeze(dim=0)\n",
    "    vec_length = torch.tensor([vec_length], dtype=torch.int64)\n",
    "    \n",
    "    result = classifier(vectorized_surname, vec_length, apply_softmax=True)\n",
    "    probability_values, indices = result.max(dim=1)\n",
    "    \n",
    "    index = indices.item()\n",
    "    prob_value = probability_values.item()\n",
    "\n",
    "    predicted_nationality = vectorizer.nationality_vocab.lookup_index(index)\n",
    "\n",
    "    return {'nationality': predicted_nationality, 'probability': prob_value, 'surname': surname}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'nationality': 'Irish', 'probability': 0.339665025472641, 'surname': 'McMahan'}\n",
      "{'nationality': 'Italian', 'probability': 0.49502408504486084, 'surname': 'Nakamoto'}\n",
      "{'nationality': 'Korean', 'probability': 0.40598589181900024, 'surname': 'Wan'}\n",
      "{'nationality': 'Vietnamese', 'probability': 0.47757571935653687, 'surname': 'Cho'}\n"
     ]
    }
   ],
   "source": [
    "# surname = input(\"Enter a surname: \")\n",
    "classifier = classifier.to(\"cpu\")\n",
    "for surname in ['McMahan', 'Nakamoto', 'Wan', 'Cho']:\n",
    "    print(predict_nationality(surname, classifier, vectorizer))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "nlpbook",
   "language": "python",
   "name": "nlpbook"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.2"
  },
  "toc": {
   "colors": {
    "hover_highlight": "#DAA520",
    "running_highlight": "#FF0000",
    "selected_highlight": "#FFD700"
   },
   "moveMenuLeft": true,
   "nav_menu": {
    "height": "120px",
    "width": "252px"
   },
   "navigate_menu": true,
   "number_sections": true,
   "sideBar": true,
   "threshold": "5",
   "toc_cell": false,
   "toc_section_display": "block",
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
